package com.chenjiajin.web.advice;

import com.chenjiajin.domain.ResultCode;
import com.chenjiajin.domain.ResultVo;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 */
@RestControllerAdvice
public class ControllerExceptionAdvice {

    @ExceptionHandler({BindException.class})
    public ResultVo MethodArgumentNotValidExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }


    @ExceptionHandler({RuntimeException.class})
    public ResultVo MethodArgumentNotValidExceptionHandler(RuntimeException e) {
        String message = e.getMessage();
        return new ResultVo(ResultCode.VALIDATE_ERROR, message);
    }

    @ExceptionHandler({Exception.class})
    public ResultVo MethodArgumentNotValidExceptionHandler(Exception e) {
        String message = e.getMessage();
        return new ResultVo(ResultCode.VALIDATE_ERROR, message);
    }


}